package com.micro.shop.aop;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.micro.shop.annotation.H5AuthAnnotion;
import com.micro.shop.core.ErrorCode.H5Error;
import com.micro.shop.core.exception.AppException;
import com.micro.shop.redis.RedisWechatApptoken;
import com.micro.shop.utils.ThreadLocalUtils;

/**  
 * h5页面认证aop   
 * @ClassName: H5AuthAspect    
 * @date 2017年5月21日 下午4:21:23    
 * @version  v 1.0    
 */
@Component
@Aspect
public class H5AuthAspect {
	
	@Autowired
	private RedisWechatApptoken redisH5token;
	
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	/**
	 * 前置通知
	 * @param joinPoint 调用的方法
	 * @param auth
	 */
	@Before(value="@annotation(h5Auth)")
	public void beforeAuth(JoinPoint joinPoint,H5AuthAnnotion h5Auth) {
		Object[] objects = joinPoint.getArgs();
		if(objects.length>=1){
			HttpServletRequest request = null;
			for(Object obj:objects){
				if(obj instanceof HttpServletRequest){
					request = (HttpServletRequest)obj;
					break;
				}
			}
			if(request == null){
				throw new AppException("认证注解H5AuthAnnotion参数参数必须有一个是HttpServletRequest");
			}
			//获取cookies
			String token = request.getHeader("token");
			if(StringUtils.isBlank(token)){
				throw new AppException(H5Error.H5TOKEN_INVALID);
			}
			boolean flag = redisH5token.isExistH5token(token);
			if(flag){
				ThreadLocalUtils.setH5token(token);
				redisH5token.updateH5TokenExpire(token, 7*24*60*60);
			}else{
				throw new AppException(H5Error.H5TOKEN_INVALID);
			}
		}else{
			throw new AppException("认证注解H5AuthAnnotion参数参数必须有一个是HttpServletRequest");
		}
	}
	
	/**
	 * 后置通知
	 * @param joinPoint 调用的方法
	 * @param auth
	 */
	@After(value="@annotation(h5Auth)")
	public void afterAuth(JoinPoint joinPoint,H5AuthAnnotion h5Auth) {
		logger.info("after 清楚当前线程的session H5token={} , threadname={} ", ThreadLocalUtils.getH5token(), Thread.currentThread().getName());
		ThreadLocalUtils.removeH5token();
	}
}
